//
//  PushService.swift
//  QNN
//
//  Created by zhenyu on 17/5/12.
//  Copyright © 2017年 qianshengqian. All rights reserved.
//

import UIKit

class Transition {
  
  // MARK: - RootVC
  static func rootVC() -> TabBarController {
    return window?.rootViewController as! TabBarController
  }
  
  static func navigation() -> NavigationController? {
    if let presentedViewController = rootVC().presentedViewController {
      return presentedViewController as? NavigationController
    } else {
      return rootVC().selectedViewController as? NavigationController
    }
  }
  
  // MARK: - push
  static func push(vc: UIViewController) {
    if let navi = navigation() {
      navi.pushViewController(vc, animated: true)
    }
  }
  
  static func pushWebVC(urlStr: String) {
    if let _ = urlStr.toURL() {
      let vc = WebViewController(url: urlStr)
      push(vc: vc)
    }
  }
  
  // MARK: - present
  static func present(vc: UIViewController, completion: (()->())?) {
    if let presentedViewController = rootVC().presentedViewController {
      presentedViewController.present(vc, animated: true, completion: completion)
    } else {
      rootVC().selectedViewController?.present(vc, animated: true, completion: completion)
    }
  }
  
  
  // MARK: - PopBack
  static func popToRoot() {
    if let navi = navigation() {
      navi.popToRootViewController(animated: true)
    }
  }
  
  static func popBack() {
    if let navi = navigation() {
      navi.popViewController(animated: true)
    }
  }
}


// TODO: - Add to Extension
extension String {
  public var length: Int { return self.characters.count }
  
  public func toURL() -> NSURL? {
    return NSURL(string: self)
  }
}
